﻿namespace MonetDbDataProvider.Mapi
{
    using System;

    public class Utility
    {
        public ChallengeResponse ParseChallenge(string challenge, string username, string password)
        {
            var protocolVersion = 0;
            var serverType = string.Empty;
            var challengeUsername = username;
            var challengePassword = password;

            var tokens = challenge.Split(':');

            if (tokens.Length <= 4)
            {
                throw new ArgumentException(
                    "Server challenge string unusable. Challenge contains too few tokens: " + challenge);
            }
            
            if (tokens[1].Equals("merovingian"))
            {
                challengeUsername = "merovingian";
                challengePassword = "merovingian";
            }

            int.TryParse(tokens[2], out protocolVersion);

            if (protocolVersion != 9)
            {
                throw new ArgumentException(string.Format("Unsupported protocol version: {0}", protocolVersion));
            }

            return new ChallengeResponse()
                       {
                           ChallengeHash = tokens[0],
                           ServerType = serverType,
                           Hash = tokens[3],
                           ProtocolVersion = protocolVersion,
                           Username = challengeUsername,
                           Password = challengePassword,
                           ByteOrder = tokens[4]
                       };
        }
    }
}
